package stream

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/lexkong/log"
	"github.com/segmentio/ksuid"
	"net/http"
	"os"
	"time"
	"webProject/handler"
	"webProject/model"
	"webProject/pkg/constvar"
)

func DownLoadHandler(c *gin.Context){
	vid := c.Query("vid")
	getVideo, e := model.GetVideo(vid)
	if e!=nil{
		log.Infof("Error when try to get Vedio %v",e)
	}
	vl := getVideo.FilePath
	video, err := os.Open(vl)
	if err!=nil{
		log.Infof("Error when try to open file: %v", err)
		handler.SendResponse(c,err,"Internal Error")
		return
	}
	c.Writer.Header().Set("Content-Type","video/mp4")
	http.ServeContent(c.Writer, c.Request, "", time.Now(), video)
	defer video.Close()
}


func UploadHandler(c *gin.Context){
	file, _ := c.FormFile("file")
	log.Info(file.Filename)
	// 上传文件到指定的路径
	dst := constvar.VideosDir+file.Filename
	if err := c.SaveUploadedFile(file, dst);err!=nil{
		c.String(http.StatusInternalServerError,fmt.Sprintf("uploaded fail err: %s",err.Error()))
		return
	}
	//生成唯一ID
	//将视频信息写入到数据库
	vid := ksuid.New()
	video:=model.Video{
		VId:       vid.String(),
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
		DeletedAt: nil,
		FilePath:  dst,
	}
	video.CreateVideo()
	c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!As vid %s", file.Filename,vid.String()))
}


